import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  setToken(state, data) {
    state.token = data
    setToken(data)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  getInfo(state, data) {
    state.userInfo = data
  },
  removeInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录
  async login(context, obj) {
    console.log(obj)
    const res = await login(obj)
    console.log(res, 'res-========')
    context.commit('setToken', res.token)
  },

  // get user info
  async getInfo(context) {
    const res = await getInfo()
    console.log(res, '用户信息-----------')
    context.commit('getInfo', res)
  },

  // user logout
  async logout(context) {
    const res = await logout()
    console.log(res, 'logout---')
    context.commit('removeInfo')
    context.commit('removeToken')
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

